$(document).ready(function()
{
	
	/*
	 * addTagToMedia
	 */
	function addTagToMedia(sha256Hash, tag) {
		jsonData = {
			"cmd": "ajax",
			"func": "mediaAddTag",
			"sha256Hash": sha256Hash,
			"tag": tag
		}
		$.getJSON('/pdrive', jsonData, function(data) {
			if (data.status == "OK") {
				console.log("tag added");
				return true;
			}
			console.log("Failed to add tag to media");
			console.log(data);
			return false;
		});
	}

	/*
	 * ajax
	 */
	function ajax(jsonData, command, successFunction) {
		username = getSessionVar("username")
		psk = getSessionVar("psk")
		dateStamp = new Date().toUTCString();
		signature = CryptoJS.HmacSHA256(CryptoJS.HmacSHA256(username, dateStamp).toString(), CryptoJS.HmacSHA256(psk, command).toString())
		return $.ajax({
			type: "POST",
			url: "/pdrive/" + command,
			data: jsonData,
			dataType: "json",
			beforeSend: function(xhr) {
				xhr.setRequestHeader('X-Signature', signature);
				xhr.setRequestHeader('X-Date', dateStamp);
			},
			success: successFunction
		})
	}

	/*
	 * authSession
	 */
	function authSession() {
		// pre-shared key; prior to real auth
		// var psk = "H6QB4Z57LHX2MNJS";
		username = prompt("Name")
		auth = prompt("Auth")
		sessionStorage.setItem("username", username)
		sessionStorage.setItem("auth", auth)
		var authPostResponse = $.post("/pdrive/auth", {"username": username, "auth": auth}, function (data) {
			if (data.status == "OK") {
				sessionStorage.setItem("psk", data.psk)
			} else {
				sessionStorage.setItem("psk", "false")
			}
			location.reload();
		});
	}

	/*
	 * checkHMAC
	 */
	function checkHMAC(httpResponse) {
		var psk = getSessionVar("psk");
		var signature = httpResponse.getResponseHeader("x-signature");
		var headerDate = JSDate2epoch(httpResponse.getResponseHeader("Date"));
		if (Math.abs(headerDate - JSDate2epoch()) > 1800) {
			console.log("Server and brosers clocks are > 60 seconds apart");
			console.log("HeaderDate:  " + headerDate);
			console.log("BrowserDate:  " + JSDate2epoch());
		}
		var hash = CryptoJS.HmacSHA256(httpResponse.responseText, headerDate.toString() + "::" + psk + "::" + getSessionVar("username"));
		if (signature != hash) {
			console.log("Sig: " + signature)
			console.log("headerDate: " + headerDate)
			console.log("hash: " + hash)
			return false;
		}
		return true;
	}

	/*
	 * dateFromEpoch
	 */
	function dateFromEpoch(secs) {
		dt = new Date(parseInt(secs, 10));
		return dt.toISOString();
	}


	/*
	 * epoch2JSDate
	 */
	function epoch2JSDate(secs) {
		return new Date(secs * 1000);
	}

	/*
	 * getSessionVar
	 */
	function getSessionVar(itemKey) {
		if (sessionStorage.getItem(itemKey)) {
			return sessionStorage.getItem(itemKey);
		}
		return undefined;
	}


	/*
	 * JSDate2epoch
	 */
	function JSDate2epoch(dateString) {
		if (dateString == undefined) {
			var seconds = new Date();
		} else {
			var seconds = new Date(dateString);
		}
		epoch = (seconds / 1000) | 0;
		return epoch;
	}
	
	/*
	 * loadTags
	 */
	function loadTags() {
		$('#tagList').html('');
		// Load up and display the tags
		jsonData = {
				"username": getSessionVar("username")
			};
			var getTagsResponse = ajax(jsonData, "getTags", function(data) {
				if (checkHMAC(getTagsResponse)) {
					if (data.status != "OK") {
						console.log("Error from server (" + data.code + "): '" + data.message +"'")
						return false
					}
					var tagArray = [];
					$.each(data.tagList, function(tagObj) {
						//console.log(data.tagList[tagObj])
						tag = data.tagList[tagObj]
						tagArray.push(tag.tag)
						//console.log(tagObj)
						$('#tagList').append('<li id="_tag' + tag.id + '"><label class="checkbox"><input type="checkbox" id="_tag_checkbox_-_' + tag.id + '" CHECKED>' + tag.tag + ' (' + tag.useCount + ')</label></li>');
					});
					sessionStorage.setItem("fullTagList", tagArray.join("%^%"));
					$(":checkbox").change(function () {
						tagChange();
					});
					// This will load up the media list
					tagState = sessionStorage.getItem("tagList");
					if (tagState == "--noTags") {
						$("#tagList").find(":checkbox").prop('checked', false);
					} else if (tagState == "--allTags") {
						$("#tagList").find(":checkbox").prop('checked', true);
					} else if ((tagState != undefined) || (tagState != null)) {
						$("#tagList").find(":checkbox").prop('checked', false);
						$.each(tagState.split("|"), function(ndx, tagID) {
							$("#_tag_checkbox_-_" + tagID).prop('checked', true);
						});
					}
			
					tagChange();
				} else {
					console.log("getTags: Signature: BAD");
				}
		});
	}

	/*
	 * loadMediaList -- New Layout
	 */
	function loadMediaList(obj) {
		// SessionStorage vars
		var mediaTypeLimit = getSessionVar("mediaTypeLimit");
		var fileTypeLimit = getSessionVar("fileTypeLimit");
		var fullTextSearch = getSessionVar("fullTextSearch")
		var tagList = getSessionVar("tagList")
		if (mediaTypeLimit == undefined) {
			$("#_dropdownButton_mediaType").html("Media: (all) ");
		} else {
			$("#_dropdownButton_mediaType").html("Media: " + mediaTypeLimit + " ");
		}
		if (fileTypeLimit == undefined) {
			$("#_dropdownButton_fileType").html("File: (all) ");
		} else {
			$("#_dropdownButton_fileType").html("File: " + fileTypeLimit + " ");
		}
		
		$("#_mediaList_table_body").html("")
		jsonData = {
			"mediaTypeLimit": mediaTypeLimit,
			"fileTypeLimit": fileTypeLimit,
			"textLimit": fullTextSearch,
			"tagList": tagList,
			"username": getSessionVar("username")
		}

		var getMediaListResponse = ajax(jsonData, "getMediaList", function(data) {
			if (checkHMAC(getMediaListResponse)) {
				if (data.status != "OK") {
					console.log("Error from server (" + data.code + "): '" + data.message +"'")
					return false
				}
				mediaListCount = data.mediaListCount;
				mediaCountText = "0 Media Files Listed";
				if (mediaListCount > 1) {
					mediaCountText = mediaListCount + " Media Files Listed";
				} else if (mediaListCount == 1) {
					mediaCountText = mediaListCount + " Media File Listed";
				}
					
				$("#_mediaCount").html('<span class="label label-info">' + mediaCountText + '</span>');
				var thumbnails = "";
				$.each(data.mediaList, function(mediaObj) {
					media = data.mediaList[mediaObj]
					var descr;
					if (media.descr != null) {
						descr = media.descr;
					} else {
						descr = media.filename;
					}

					var id
					var playButton = "";
					if (media.fileType == "mp4") {
						id = "_mediaVideo_-_" + media.sha256Hash;
						playButton = '&nbsp;<a class="btn btn-mini" id="' + id + '" href="#"><i class="icon-play"></i></a>';
						
					}
					if (media.mediaType == "image") {
						id = "_mediaImage_-_" + media.sha256Hash;
						playButton = '&nbsp;<a class="btn btn-mini" id="' + id + '" href="#"><i class="icon-play"></i></a>';
					}
					dlPath = media.relpath;
					dlLink = '<a target="_dlFile" class="btn btn-mini" href="' + dlPath + '"><i class="icon-download"></i></a>';
					infoLink = '<a id="_info_-_' + media.sha256Hash + '" class="btn btn-mini" href="#"><i class="icon-info-sign"></i></a>';
					functionLinks = dlLink + '&nbsp;' + infoLink + playButton;
					var stars = ""
					if (media.rating == null) {
						media.rating = 0;
					}
					for (var i = 0; i < media.rating; i++) {
						stars = stars + '<i class="icon-star"></i>';
					}
					for (var i = 0; i < (5 - media.rating); i++) {
						stars = stars + '<i class="icon-star-empty"></i>';
					}
					var tags = "";
					$.each(media.tags, function (ndx, tag) {
						tags = tags + '<span class="label">' + tag + '</span>&nbsp;';
					});
					mediaType = media.mediaType;
					if (media.mediaType == "video") {
						mediaType = '<i class="icon-film"></i>';
					} else if (media.mediaType == "image") {
						mediaType = '<i class="icon-picture"></i>';
					} else {
						mediaType = '<i class="icon-fike"></i>';
					}
					
					
					if (id != undefined) {
						$("#" + id).click(function() { showMedia($(this)); });
					}
					$("#_info_-_" + media.sha256Hash).click( function() { mediaInfo($(this)); });
					
					if (media.thumbnailPath == "") {
						if (media.fileType == "plain") {
							media.thumbnailPath = "/pres/img/text-icon.png";
						} else {
							media.thumbnailPath = "/pres/img/generic-file.png";
						}
					}
					var id = "__showThumb_-_" + media.sha256Hash;
					thumbnails = thumbnails + '<li class="span2">';
					thumbnails = thumbnails + '<a id="' + id + '" class="thumbnail">';
					thumbnails = thumbnails + '<img class="img-rounded shadow lazy" src="/pres/img/generic-file.png" data-original="' + media.thumbnailPath + '">';
					thumbnails = thumbnails + '</a>';
					thumbnails = thumbnails + '<div class="center-text">' + stars + dlLink + '</div>';
					thumbnails = thumbnails + '</li>';
				});
				$("#mediaThumbnails").html(thumbnails);
				$("img.lazy").lazyload({effect: "fadeIn"});
				$("#mediaThumbnails").find("a").click(function() {
					sha256Hash = $(this).attr("id").split("_-_")[1];
					jsonData = {
							"sha256Hash": sha256Hash,
							"thumbSize": 1,
							"username": getSessionVar("username")
					};
					var getMediaListResponse = ajax(jsonData, "showImage", function(data) {
						if (checkHMAC(getMediaListResponse)) {
							if (data.status != "OK") {
								console.log("Error from server (" + data.code + "): '" + data.message +"'")
								if (data.code == 201) {
									authSession();	
								}
								return false
							}
							imageURL = data.imageURL;
							$("#imageModal_image").attr("src", imageURL)
							//$("#imageModal_overlay").css("background", "url(" + imageURL + ") no-repeat center center");
							$("#imageModal_wrapper").css("display", "block");
							$("#imageModal_wrapper").css("visibility", "visible");
							$("#imageModal_overlay").click(function(){
								$("#imageModal_wrapper").css("display", "none");
								$("#imageModal_wrapper").css("visibility", "hidden");
							})
						}
					});
				});
			} else {
				console.log("getMediaList: Signature: BAD");
			}
			
		});	
	}


	/*
	 * mediaInfo
	 */
	function mediaInfo(obj) {
		var rawTagList = getSessionVar("fullTagList");
		fullTagList = rawTagList.split("%^%");
		id = $(obj).attr("id");
		sha256Hash = id.split("_-_")[1]
		if (sha256Hash == undefined) {
			console.log("Tried to do 'mediaInfo(obj)', but split yeided undefined. obj id is '" + id + "'");
			alert("something went very wrong... check the console logs");
			return;
		}
		jsonData = {
			"sha256Hash": sha256Hash,
			"username": getSessionVar("username")
		};
		var getMediaListResponse = ajax(jsonData, "getMediaList", function(data) {
			if (checkHMAC(getMediaListResponse)) {
				var row;
				$.each(data.mediaList, function(mediaObj) {
					media = data.mediaList[mediaObj];
					rating = media.rating;
					descr = media.descr;
					sha256Hash = media.sha256Hash;
					rawTags = media.tags;
					filesize = media.filesize;
					fileType = media.fileType;
					relpath = media.relpath;
					webRelpath = media.webRelpath;
					mediaType = media.mediaType;
					filename = media.filename;
					mtime = media.mtime;
					atime = media.atime;
					chtime = media.chtime;
					commitDate = media.commitDate;
					s3 = media.s3;
					directory = media.directory;

					if (s3 == null) {
						s3 = "No";
					}
					if (descr == null) {
						descr = "";
					}
					if (rating == null) {
						rating = 0;
					}
					stars = rating;
					descriptionBox = '<div class="input-append">';
					descriptionBox = descriptionBox + '<input class="span5" id="_mediaDescr" type="text" value="' + descr  + '">';
					descriptionBox = descriptionBox + '<button class="btn" id="_mediaDescrUpdate" type="button"><i class="icon-ok"></i></button>';
					descriptionBox = descriptionBox + '<button class="btn" id="_mediaDescrClear" type="button"><i class="icon-remove"></i></button>';

					var tags = "";
					$.each(fullTagList, function(ndx, tag) {
						if (rawTags.indexOf(tag) != -1) {
							tags = tags + '<button id="_mediaTag_-_' + tag + '" class="btn btn-mini btn-success" type="button">' + tag + '</button>&nbsp;';
						} else {
							tags = tags + '<button id="_mediaTag_-_' + tag + '" class="btn btn-mini btn-inverse">' + tag + '</button>&nbsp;';
						}
					});
					
					row = "";
					row = row + "<tr><td>File Name</td><td>" + filename  + "</td></tr>";
					row = row + "<tr><td>Import Directory</td><td>" + directory  + "</td></tr>";
					row = row + "<tr><td>sha256 Hash</td><td>" + sha256Hash  + "</td></tr>";
					row = row + "<tr><td>Description</td><td>" + descriptionBox + "</td></tr>";
					row = row + "<tr><td>Rateing</td><td>" + stars  + "</td></tr>";
					row = row + '<tr><td>Tags</td><td><div id="__mediaTags">' + tags  + '</div></td></tr>';
					row = row + "<tr><td>Media Type</td><td>" + mediaType  + "</td></tr>";
					row = row + "<tr><td>File Type></td><td>" + fileType  + "</td></tr>";
					row = row + "<tr><td>File Size</td><td>" + filesize  + "</td></tr>";
					row = row + "<tr><td>pDrive Commit Date</td><td>" + dateFromEpoch(commitDate)  + " (" + commitDate + ")</td></tr>";
					row = row + "<tr><td>Sync'ed S3</td><td>" + s3  + "</td></tr>";
					row = row + "<tr><td>atime</td><td>" + atime  + "</td></tr>";
					row = row + "<tr><td>mtime</td><td>" + mtime  + "</td></tr>";
					row = row + "<tr><td>chtime</td><td>" + chtime  + "</td></tr>";
					row = row + "<tr><td>Path To File</td><td>" + relpath  + "</td></tr>";
					row = row + "<tr><td>Path To WebFile</td><td>" + webRelpath  + "</td></tr>";

				});
				table = '<table class="table"><tbody>' + row + '</tbody></table>';
				div = '<div class="_mediaInfo">' + table + '</div>';
				$("#generalModal_content").html(div);
				$("#generalModal_body").css("height", "75%");
				$("#generalModal_body").css("width", "75%");
				$("#generalModal_wrapper").css("display", "block");
				$("#generalModal_wrapper").css("visibility", "visible");
				$("#_mediaDescrUpdate").click(function() {
					updateDescr(sha256Hash, $("#_mediaDescr").val());
				});
				$("#_mediaDescrClear").click(function() {
					updateDescr(sha256Hash, undefined);
				});
				$("#__mediaTags").find(".btn").click(function() {
					tagName = $(this).attr("id").split("_-_")[1];
					if ($(this).attr("class").search("success") > 0) {
						removeTagFromMedia(sha256Hash, tagName);
						$(this).removeClass("btn-success");
						$(this).addClass("btn-inverse");
					} else {
						addTagToMedia(sha256Hash, tagName);
						$(this).addClass("btn-success");
						$(this).removeClass("btn-inverse");
					}
				});
			}
		});
	}
	
	
	function removeTagFromMedia(sha256Hash, tag) {
		jsonData = {
			"cmd": "ajax",
			"func": "mediaRmTag",
			"sha256Hash": sha256Hash,
			"tag": tag
		}
		$.getJSON('/pdrive', jsonData, function(data) {
			if (data.status == "OK") {
				console.log("tag removed")
				return true;
			}
			console.log("Failed to remove tag from media");
			console.log(data);
			return false;
		});
	}
		
	function updateDescr(sha256Hash, descr) {
		if (descr == undefined) {
			descr = "";
		}
		jsonData = {
			"cmd": "ajax",
			"func": "setMediaDescr",
			"sha256Hash": sha256Hash,
			"descr": descr
		}
		$.getJSON('/pdrive', jsonData, function(data) {
			if (data.status == "OK") {
				$("#_mediaDescr").val(data.descr);
			} else {
				alert("Bad data returned. See console log.");
				console.log(data);
			}
		});
	}
	function tagAdd() {
		form = '<form><fieldset><legend>Add New Tag</legend><div class="input-append"><input class="span3" id="_addNewTagValue" type="text"><button class="btn" id="_cmdAddTag" type="button"><i class="icon-ok"></i></button></div></fieldset></form>';
		$("._overlayContent").html(form);
		$("._overlayBody").css("height", "175px");
		$("._overlayBody").css("width", "400px");
		$("._overlayWrapper").css("display", "block");
		$("._overlayWrapper").css("visibility", "visible");
		$("#_cmdAddTag").click(function () {
			var newtag = $("#_addNewTagValue").val();
			if ( (newtag == null) || (newtag == "") || (newtag == undefined) ) {
				alert("You must enter a new tag... or close the box.");
			}
			jsonData = {
				"cmd": "ajax",
				"func": "tagAdd",
				"tag": newtag
			}
			$.getJSON('/pdrive', jsonData, function(data) {
				if (data.status != "OK") {
					console.log(data)
					alert("Something bad happened adding the tag! See the console log.");
				}
				$("._overlayWrapper").css("visibility", "hidden"); 
				$("._overlayWrapper").css("display", "none"); 
				loadTags();
			});
		});
		
	}

	function tagRemove() {
		var rawTagList = getSessionVar("fullTagList").split("%^%");
		var tags = '<div id="__removeTags">'
		$.each(rawTagList, function(ndx, tag) {
			tags = tags + '<button id="_mediaTag_-_' + tag + '" class="btn btn-mini btn-inverse">' + tag + '</button>&nbsp;';
		});
		tags = tags + '</div>';
		$("._overlayContent").html(tags);
		$("._overlayBody").css("height", "500px");
		$("._overlayBody").css("width", "700px");
		$("._overlayWrapper").css("display", "block");
		$("._overlayWrapper").css("visibility", "visible");
		$("#__removeTags").find(".btn").click(function() {
			tagName = $(this).attr("id").split("_-_")[1];
			if ($(this).attr("class").search("success") > 0) {
				$(this).removeClass("btn-success");
				$(this).addClass("btn-inverse");
			} else {
				$(this).addClass("btn-success");
				$(this).removeClass("btn-inverse");
			}
		});
	}

	function tagChange() {
		tagsChecked = []
		allChecked = true;
		$.each($("#tagList").find(":checkbox"), function() {
			if ($(this).prop('checked') == true) {
				tagID = $(this).attr("id").split('_-_')[1];
				tagsChecked.push(tagID)
			} else {
				allChecked = false;
			}
		});
		if (allChecked == true) {
			tagList = "--allTags";
		} else {
			tagList = tagsChecked.join("|")
			if (tagList == "") {
				tagList = "--noTags";
			}
		}
		//console.log(tagList)
		sessionStorage.setItem("tagList", tagList);
		loadMediaList()
	}

	function showMedia(obj) {
		func = obj.attr("id").split('_-_')[0];
		sha256Hash = obj.attr("id").split('_-_')[1];
		if (func == "_mediaImage") {
			jsonData = {
					"sha256Hash": sha256Hash,
					"username": getSessionVar("username")
			};
			var getMediaListResponse = ajax(jsonData, "showImage", function(data) {
				if (checkHMAC(getMediaListResponse)) {
					if (data.status != "OK") {
						console.log("Error from server (" + data.code + "): '" + data.message +"'")
						if (data.code == 201) {
							authSession();	
						}
						return false
					}
					imageURL = data.imageURL;
					$("._overlayContent").html('<img style="margin-top: 20px" class="img-rounded" src="' + imageURL + '">');
					$("._overlayBody").css("height", "550px");
					$("._overlayBody").css("width", "660px");
					$("._overlayWrapper").css("display", "block");
					$("._overlayWrapper").css("visibility", "visible");
				}
			});
		} else if (func == "_mediaVideo") {
			jsonData = {
				"cmd": "ajax",
				"func": "showVideo",
				"sha256Hash": sha256Hash
			}
			$.getJSON('/pdrive', jsonData, function(data) {
				videoURL = data.videoURL;
				$("._overlayContent").html('<video id="_videoPlayer" class="video-js vjs-default-skin"></video>');
				_V_("_videoPlayer", {"controls": true, "autoplay": false, "preload": "auto"}, function(){
					var player = this;
					player.width(569);
					player.height(320);
					player.src({ type: "video/mp4", src: videoURL});
				});
				$("._overlayBody").css("width", "590px");
				$("._overlayBody").css("height", "380px");
				$("._overlayWrapper").css("display", "block");
				$("._overlayWrapper").css("visibility", "visible");
			});
			
		}
	}

	// Load up and display the media list
	function OldloadMediaList() {
		// SessionStorage vars
		var mediaTypeLimit = getSessionVar("mediaTypeLimit");
		var fileTypeLimit = getSessionVar("fileTypeLimit");
		var fullTextSearch = getSessionVar("fullTextSearch")
		var tagList = getSessionVar("tagList")
		if (mediaTypeLimit == undefined) {
			$("#_dropdownButton_mediaType").html("Media: (all) ");
		} else {
			$("#_dropdownButton_mediaType").html("Media: " + mediaTypeLimit + " ");
		}
		if (fileTypeLimit == undefined) {
			$("#_dropdownButton_fileType").html("File: (all) ");
		} else {
			$("#_dropdownButton_fileType").html("File: " + fileTypeLimit + " ");
		}
		
		$("#_mediaList_table_body").html("")
		jsonData = {
			"mediaTypeLimit": mediaTypeLimit,
			"fileTypeLimit": fileTypeLimit,
			"textLimit": fullTextSearch,
			"tagList": tagList,
			"username": getSessionVar("username")
		}

		var getMediaListResponse = ajax(jsonData, "getMediaList", function(data) {
			if (checkHMAC(getMediaListResponse)) {
				//console.log(data)
				mediaListCount = data.mediaListCount;
				mediaCountText = "0 Media Files Listed";
				if (mediaListCount > 1) {
					mediaCountText = mediaListCount + " Media Files Listed";
				} else if (mediaListCount == 1) {
					mediaCountText = mediaListCount + " Media File Listed";
				}
					
				$("#_mediaCount").html('<span class="label label-info">' + mediaCountText + '</span>');
				//$("#_mediaList_table").dataTable({"bDestroy": true, "aaData": data.mediaList});
				// Clear the carousel
				$("#myCarousel_items").html('');
				$.each(data.mediaList, function(mediaObj) {
					//console.log(data.mediaList[mediaObj])
					media = data.mediaList[mediaObj]
					//console.log(media)
					if (media.webRelpath) {
						$("#myCarousel_items").append('<div class="item"><img src="' + media.webRelpath + '"></div>');
					}
					var descr;
					if (media.descr != null) {
						descr = media.descr;
					} else {
						descr = media.filename;
					}

					var id
					var playButton = "";
					if (media.fileType == "mp4") {
						id = "_mediaVideo_-_" + media.sha256Hash;
						playButton = '&nbsp;<a class="btn btn-mini" id="' + id + '" href="#"><i class="icon-play"></i></a>';
						
					}
					if (media.mediaType == "image") {
						id = "_mediaImage_-_" + media.sha256Hash;
						playButton = '&nbsp;<a class="btn btn-mini" id="' + id + '" href="#"><i class="icon-play"></i></a>';
					}
					dlPath = media.relpath;
					dlLink = '<a target="_dlFile" class="btn btn-mini" href="' + dlPath + '"><i class="icon-download"></i></a>';
					infoLink = '<a id="_info_-_' + media.sha256Hash + '" class="btn btn-mini" href="#"><i class="icon-info-sign"></i></a>';
					functionLinks = dlLink + '&nbsp;' + infoLink + playButton;
					var stars = ""
					if (media.rating == null) {
						media.rating = 0;
					}
					for (var i = 0; i < media.rating; i++) {
						stars = stars + '<i class="icon-star"></i>';
					}
					for (var i = 0; i < (5 - media.rating); i++) {
						stars = stars + '<i class="icon-star-empty"></i>';
					}
					var tags = "";
					$.each(media.tags, function (ndx, tag) {
						tags = tags + '<span class="label">' + tag + '</span>&nbsp;';
					});
					mediaType = media.mediaType;
					if (media.mediaType == "video") {
						mediaType = '<i class="icon-film"></i>';
					} else if (media.mediaType == "image") {
						mediaType = '<i class="icon-picture"></i>';
					} else {
						mediaType = '<i class="icon-fike"></i>';
					}
					
					$('#_mediaList_table_body').append('<tr><td class="nowrap" style="text-align: center;">' + functionLinks + '</td><td>' + mediaType + '&nbsp;' + descr  + '</td><td class="nowrap" style="text-align: center;">' + stars + '</td><td>' + tags + '</td></tr>');
					if (id != undefined) {
						$("#" + id).click(function() { showMedia($(this)); });
					}
					$("#_info_-_" + media.sha256Hash).click( function() { mediaInfo($(this)); });
					
		
				});
			} else {
				console.log("getMediaList: Signature: BAD");
			}
			
		});
		
	}

	// When a media type is selected, store it in the session data and relaod the media list
	function changeMediaType(obj) {
		id = obj.attr('id');
		parts = id.split('-_-');
		mediaTypeLimit = parts[1]
		//console.log(mediaTypeLimit);
		sessionStorage.setItem("mediaTypeLimit", mediaTypeLimit);
		loadMediaList();
	}
	
	// When a file type is selected, store it in the session data and relaod the media list
	function changeFileType(obj) {
		id = obj.attr('id');
		parts = id.split('-_-');
		fileTypeLimit = parts[1]
		//console.log(fileTypeLimit);
		sessionStorage.setItem("fileTypeLimit", fileTypeLimit);
		loadMediaList();
	}

	


	/*
	 * End of Functions.
	 * Beginning of Script.
	 */
	
	// Auth will need to occur...
	var psk = getSessionVar("psk");
	if ( (psk == "false") || (psk == undefined) ) {
		authSession();
	}

	// Get Media Types	
	var getMediaTypesResponse = ajax({"username": getSessionVar("username")}, "getMediaTypes", function(data) {
		if (checkHMAC(getMediaTypesResponse)) {
			if (data.status != "OK") {
				console.log("Error from server (" + data.code + "): '" + data.message +"'")
				if (data.code == 201) {
					authSession();	
				}
				return false
			}
			$.each(data.mediaTypeList, function(mediaTypeObj) {
				mediaType = data.mediaTypeList[mediaTypeObj]
				$('#_mediaLimit').append('<li><a id="_mediaTypeLimit-_-' + mediaType.type + '" href="#">' + mediaType.type + '</a></li>');
				$('#_mediaTypeLimit-_-' + mediaType.type).click(function() {
					changeMediaType($(this));
				});
			});
		} else {
			console.log("getMediaTypes: Signature: BAD");
		}
	});

	// Get File Types	
	getFileTypesResponse = $.post('/pdrive/getFileTypes', {"username": getSessionVar("username")}, function(data) {
		if (checkHMAC(getFileTypesResponse)) {
			if (data.status != "OK") {
				console.log("Error from server (" + data.code + "): '" + data.message +"'")
				return false
			}
			$.each(data.fileTypeList, function(fileTypeObj) {
				fileType = data.fileTypeList[fileTypeObj]
				$('#_fileTypeLimit').append('<li><a id="_fileTypeLimit-_-' + fileType.type + '" href="#">' + fileType.type + '</a></li>');
				$('#_fileTypeLimit-_-' + fileType.type).click(function () { 
					changeFileType($(this));
				});
			});
		} else {
			console.log("getFileTypes: Signature: BAD");
		}
	}, "json");

	// Hooking up events for fixtures
	$("#_searchButton").click(function () {
		fullTextSearch = $("#_searchText").val();
		sessionStorage.setItem("fullTextSearch", fullTextSearch);
		loadMediaList();
		
	});
	
	$("#_searchClearButton").click(function () {
		$("#_searchText").val("");
		sessionStorage.setItem("fullTextSearch", "");
		loadMediaList();
	});

	$("#_mediaTypeLimit-_-").click(function() { changeMediaType($(this)); });
	$("#_fileTypeLimit-_-").click(function() { changeFileType($(this)); });
	$("#_mediaReload").click(function() { loadMediaList(); });
	$("#_tag_refresh").click(function() { loadTags(); });
	$("#_tag_add").click(function() { tagAdd(); });
	$("#_tag_remove").click(function() { tagRemove(); });
	$("#_overlay_close").click(function() {
		$("._overlayWrapper").css("visibility", "hidden"); 
		$("._overlayWrapper").css("display", "none"); 
		_V_("_videoPlayer").destroy();
	});
	$("#_searchText").keyup(function(event) {
		if(event.keyCode == 13) {
			$("#_searchButton").click();
		}
	});
	$("#_tag_select_all").click(function() {
		//console.log("checking all");
		$("#tagList").find(":checkbox").prop('checked', true);
		tagChange();
	});
	$("#_tag_select_none").click(function() {
		//console.log("checking none");
		$("#tagList").find(":checkbox").prop('checked', false);
		tagChange();
	});

	if (getSessionVar("fullTextSearch") != undefined) {
		$("#_searchText").val(getSessionVar("fullTextSearch"));
	}

	loadTags();
});
